from sqlalchemy import Column, String, Text, Integer, Boolean, DateTime, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from datetime import datetime
import uuid

from db.base import Base


class DocumentCategory(Base):
    """文档分类模型 - 支持树形结构的分类管理"""
    __tablename__ = "document_category"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = Column(String(100), nullable=False, comment="分类名称")
    icon = Column(String(50), default="📄", comment="分类图标")
    color = Column(String(20), default="#666666", comment="分类颜色")
    description = Column(Text, comment="分类描述")
    parent_id = Column(UUID(as_uuid=True), ForeignKey("document_category.id"), comment="父分类ID")
    sort_order = Column(Integer, default=0, comment="排序顺序")
    is_system = Column(Boolean, default=False, comment="是否系统预设分类")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")

    # 关系定义
    parent = relationship("DocumentCategory", remote_side=[id], back_populates="children")
    children = relationship("DocumentCategory", back_populates="parent", cascade="all, delete-orphan")
    documents = relationship("PersonalDocument", back_populates="category")

    def __repr__(self):
        return f"<DocumentCategory(id={self.id}, name='{self.name}', parent_id={self.parent_id})>"
